package com.cloud.job.config;

import jakarta.annotation.Resource;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ContainerProperties;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 杨斌
 * 2024-12-2024-12-18
 */
@Configuration
@EnableKafka
public class KafkaConsumerConfig {
    @Resource
    private KafkaConfig kafkaConfig;
    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaConfig.getBootstrapServers());
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 1000); // 增加每次 poll 的记录数
        props.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, 104857600); // 增加每次 fetch 的最大字节数 (100 MB)
        props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 1048576); // 设置每次 fetch 的最小字节数 (1 MB)
        props.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 26214400); // 增加每个分区每次 fetch 的最大字节数 (25 MB)
        props.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, 5000); // 减少 fetch 的最大等待时间 (500 毫秒)
        props.put(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, 60000); // 增加请求超时时间为 60 秒
        props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, 120000); // 增加会话超时时间为 120 秒
        props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, 300000); // 增加最大拉取间隔时间 (300 秒)
        return new DefaultKafkaConsumerFactory<>(props);
    }


    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(ConsumerFactory<String, String> consumerFactory) {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory);
        factory.setBatchListener(true);
        // 设置 AckMode 为 MANUAL_IMMEDIATE
        factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
        return factory;
    }
}
